package org.hj.modules.oss.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.hj.common.util.oss.OssBootUtil;
import org.hj.modules.oss.entity.OSSFile;
import org.hj.modules.oss.mapper.OSSFileMapper;
import org.hj.modules.oss.service.IOSSFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service("ossFileService")
public class OSSFileServiceImpl extends ServiceImpl<OSSFileMapper, OSSFile> implements IOSSFileService {

    @Value(value="${hj.path.upload}")
    private String filePath;
	
	@Override
	public void upload(MultipartFile multipartFile) throws IOException {
		String fileName = multipartFile.getOriginalFilename();
		OSSFile ossFile = new OSSFile();
		ossFile.setFileName(fileName);
		String url = OssBootUtil.upload(multipartFile,"upload/test");
		ossFile.setUrl(url);
		this.save(ossFile);
	}

	@Override
	public boolean delete(OSSFile ossFile) {
		try {
			this.removeById(ossFile.getId());
			OssBootUtil.deleteUrl(ossFile.getUrl());
		}
		catch (Exception ex) {
			return false;
		}
		return true;
	}

	@Override
	public void uploadByLocal(MultipartFile multipartFile, String fk) {

		try {


			String url=null;

			String realName = multipartFile.getOriginalFilename();
			String endName = realName.substring(realName.lastIndexOf("."));//后缀名
			OSSFile ossFile = new OSSFile();
			ossFile.setRealName(realName);


			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");//格式化时间 String
			String date = sdf.format(new Date());
			String newFileName = date  + endName;// 新文件名 由“时间戳+uuid+后缀名”组成
			ossFile.setFileName(newFileName);

			url=filePath+newFileName;
			ossFile.setUrl(url);
			ossFile.setFk(fk);


			File file=new File(url);
			if(!file.getParentFile().exists()){
				file.mkdirs();
			}

			multipartFile.transferTo(file);

			this.save(ossFile);
		}catch (Exception e){
			e.printStackTrace();
		}


	}

}
